import * as React from "react"
import { BubbleMenu, EditorContent, EditorContext, useEditor } from "@tiptap/react"
import { getUserId } from "@/utils/token.js"

// --- Tiptap Collaboration ---
import { IndexeddbPersistence } from "y-indexeddb";
import Collaboration from '@tiptap/extension-collaboration'
import CollaborationCursor from '@/components/Tiptap/tiptap-collaboration/tiptap-collaboration-cursor'
import * as Y from 'yjs'
import { TiptapCollabProvider } from '@hocuspocus/provider'
import { createCollaborationCursor, getUserNameFromStorage, getColorByName } from '@/components/Tiptap/tiptap-collaboration/tiptap-collaboration-cursor'
// --- Tiptap Core Extensions ---
import { StarterKit } from "@tiptap/starter-kit"
import { Image } from "@tiptap/extension-image"
import Document from '@tiptap/extension-document'
import Paragraph from '@tiptap/extension-paragraph'
import Text from '@tiptap/extension-text'
import { TaskItem } from "@tiptap/extension-task-item"
import { TaskList } from "@tiptap/extension-task-list"
import { TextAlign } from "@tiptap/extension-text-align"
import { Typography } from "@tiptap/extension-typography"
import { Highlight } from "@tiptap/extension-highlight"
import { Subscript } from "@tiptap/extension-subscript"
import { Superscript } from "@tiptap/extension-superscript"
import { Underline } from "@tiptap/extension-underline"
import { Color } from '@tiptap/extension-color'
import TextStyle from '@tiptap/extension-text-style'

// --- 添加表格扩展 ---
import { Table } from '@tiptap/extension-table'
import { TableRow } from '@tiptap/extension-table-row'
import { TableCell } from '@tiptap/extension-table-cell'
import { TableHeader } from '@tiptap/extension-table-header'

// --- Custom Extensions ---
import { Link } from "@/components/Tiptap/tiptap-extension/link-extension"
import { Selection } from "@/components/Tiptap/tiptap-extension/selection-extension"
import { TrailingNode } from "@/components/Tiptap/tiptap-extension/trailing-node-extension"
// --- Tiptap Comments ---
import { 
  createCommentsExtension, 
  CommentButton, 
  CommentsSidebar, 
  createCommentsProvider 
} from '@/components/Tiptap/tiptap-comment/index'
// --- Tiptap History ---
import { 
  createHistoryExtension,
  useDocumentHistory,
  HistoryButton
} from '@/components/Tiptap/tiptap-history/index'
import { watchPreviewContent } from '@tiptap-pro/extension-collaboration-history'
// --- UI Primitives ---
import { Button } from "@/components/Tiptap/tiptap-ui-primitive/button"
import { Spacer } from "@/components/Tiptap/tiptap-ui-primitive/spacer"
import { Tooltip } from "@/components/Tiptap/tiptap-ui-primitive/tooltip"
import {
  Toolbar,
  ToolbarGroup,
  ToolbarSeparator,
} from "@/components/Tiptap/tiptap-ui-primitive/toolbar"

// --- Tiptap Node ---
import { ImageUploadNode } from "@/components/Tiptap/tiptap-node/image-upload-node/image-upload-node-extension"
import "@/components/Tiptap/tiptap-node/code-block-node/code-block-node.less"
import "@/components/Tiptap/tiptap-node/list-node/list-node.less"
import "@/components/Tiptap/tiptap-node/image-node/image-node.less"
import "@/components/Tiptap/tiptap-node/paragraph-node/paragraph-node.less"

// --- Tiptap UI ---
import { HeadingDropdownMenu } from "@/components/Tiptap/tiptap-ui/heading-dropdown-menu"
import { ImageUploadButton } from "@/components/Tiptap/tiptap-ui/image-upload-button"
import { ListDropdownMenu } from "@/components/Tiptap/tiptap-ui/list-dropdown-menu"
import { BlockQuoteButton } from "@/components/Tiptap/tiptap-ui/blockquote-button"
import { CodeBlockButton } from "@/components/Tiptap/tiptap-ui/code-block-button"
import {
  ColorHighlightPopover,
  ColorHighlightPopoverContent,
  ColorHighlightPopoverButton,
} from "@/components/Tiptap/tiptap-ui/color-highlight-popover"
import {
  LinkPopover,
  LinkContent,
  LinkButton,
} from "@/components/Tiptap/tiptap-ui/link-popover"
import { MarkButton } from "@/components/Tiptap/tiptap-ui/mark-button"
import { TextAlignButton } from "@/components/Tiptap/tiptap-ui/text-align-button"
import { UndoRedoButton } from "@/components/Tiptap/tiptap-ui/undo-redo-button"
import { ColorTextPopover } from "@/components/Tiptap/tiptap-ui/color-text-popover"

// --- Icons ---
import { ArrowLeftIcon } from "@/components/Tiptap/tiptap-icons/arrow-left-icon"
import { HighlighterIcon } from "@/components/Tiptap/tiptap-icons/highlighter-icon"
import { LinkIcon } from "@/components/Tiptap/tiptap-icons/link-icon"
import { HistoryIcon } from "@/components/Tiptap/tiptap-icons/history-icon"

// --- Hooks ---
import { useMobile } from "@/hooks/use-mobile"
import { useWindowSize } from "@/hooks/use-window-size"
import { useCursorVisibility } from "@/hooks/use-cursor-visibility"

// --- Components ---
import { ThemeToggle } from "@/components/Tiptap/tiptap-templates/simple/theme-toggle"

// --- Lib ---
import { handleImageUpload, MAX_FILE_SIZE } from "@/utils/tiptap-utils.jsx"

// --- Styles ---
import "@/styles/_variables.less"
import "@/components/Tiptap/tiptap-templates/simple/simple-editor.less"
import "@/components/Tiptap/tiptap-history/style.less"


async function getCollaborationToken(userId, documentName) {
  try {
    const response = await fetch('/api/collaboration/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        sub: userId,
        allowedDocumentNames: [documentName],
      }),
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error || 'Failed to fetch collaboration token');
    }

    const { token } = await response.json();
    return token;
  } catch (error) {
    console.error('Error fetching collaboration token:', error);
    return null;
  }
}
 
const MainToolbarContent = ({
  onHighlighterClick,
  onLinkClick,
  isMobile
}) => {
  return (
    <>
      <Spacer />
      <ToolbarGroup>
        <UndoRedoButton action="undo" />
        <UndoRedoButton action="redo" />
      </ToolbarGroup>
      <ToolbarSeparator />
      <ToolbarGroup>
        <HeadingDropdownMenu levels={[1, 2, 3, 4]} />
        <ListDropdownMenu types={["bulletList", "orderedList", "taskList"]} />
        <BlockQuoteButton />
        <CodeBlockButton />
      </ToolbarGroup>
      <ToolbarSeparator />
      <ToolbarGroup>
        <MarkButton type="bold" />
        <MarkButton type="italic" />
        <MarkButton type="strike" />
        <MarkButton type="code" />
        <MarkButton type="underline" />
        <ColorTextPopover />
        {!isMobile ? (
          <ColorHighlightPopover />
        ) : (
          <ColorHighlightPopoverButton onClick={onHighlighterClick} />
        )}
        {/* {!isMobile ? <LinkPopover /> : <LinkButton onClick={onLinkClick} />} */}
      </ToolbarGroup>
      <ToolbarSeparator />
      <ToolbarGroup>
        <MarkButton type="superscript" />
        <MarkButton type="subscript" />
      </ToolbarGroup>
      <ToolbarSeparator />
      <ToolbarGroup>
        <TextAlignButton align="left" />
        <TextAlignButton align="center" />
        <TextAlignButton align="right" />
        <TextAlignButton align="justify" />
      </ToolbarGroup>
      <ToolbarSeparator />
      <ToolbarGroup>
        <ImageUploadButton text="添加图片" />
      </ToolbarGroup>
      <Spacer />
      {isMobile && <ToolbarSeparator />}
      <ToolbarGroup>
        <ThemeToggle />
      </ToolbarGroup>
    </>
  );
}

 
const MobileToolbarContent = ({
  type,
  onBack
}) => (
  <>
    <ToolbarGroup>
      <Button data-style="ghost" onClick={onBack}>
        <ArrowLeftIcon className="tiptap-button-icon" />
        {type === "highlighter" ? (
          <HighlighterIcon className="tiptap-button-icon" />
        ) : (
          <LinkIcon className="tiptap-button-icon" />
        )}
      </Button>
    </ToolbarGroup>

    <ToolbarSeparator />

    {type === "highlighter" ? (
      <ColorHighlightPopoverContent />
    ) : (
      <LinkContent />
    )}
  </>
)

 
const SimpleEditor = React.forwardRef(function SimpleEditor({ content, onContentChange, docId }, ref) {
  const isMobile = useMobile()
  const windowSize = useWindowSize()
  const [mobileView, setMobileView] = React.useState("main")
  const [showComments, setShowComments] = React.useState(false)
  const [showHistory, setShowHistory] = React.useState(false)
  const toolbarRef = React.useRef(null)
  const onHighlighterClick = () => setMobileView("highlighter");

  // 创建协同编辑文档和提供者
  const { provider: mainProvider, doc: mainDoc, currentUser } = React.useMemo(() => {
    const doc = new Y.Doc()
    // Set up IndexedDB for local storage of the Vdocument
    new IndexeddbPersistence(`document-${docId}`,doc)
    const userId = getUserId()
    const documentName = docId ? `document-${docId}` : 'document-default'
    const token = getCollaborationToken(userId, documentName)
    if (!token) {
      console.error("Failed to retrieve collaboration token, collaboration disabled.");
      return;
    }
    console.log('token', token)
    const currentUser = {
      name: getUserNameFromStorage(),
      color: getColorByName(getUserNameFromStorage()),
    }
    const provider = new TiptapCollabProvider({
      name: docId ? `document-${docId}` : 'document-default',
      appId: import.meta.env.VITE_TIPTAP_APP_ID,
      document: doc,
      token: token,
      onOpen() {
        console.log('WebSocket connection opened.')
      },
      onConnect() {
        console.log('Connected to the server.')
      },
      connect:true, //初始化后连接到服务器
      broadcast: true, // 实现跨浏览器标签页的文档同步
      preserveConnection:true, // 关闭提供程序后保持 WebSocket 连接打开
    })
    // Set the awareness field for the current user
    provider.setAwarenessField('user', {
      name: getUserNameFromStorage(),
      color: getColorByName(getUserNameFromStorage()),
    })
    // Listen for updates to the states of all users
    provider.on('awarenessChange', ({ states }) => {
      
    })
    // Listen for mouse movement
    document.addEventListener('mousemove', (event) => {
      // Share any information you like
      provider.setAwarenessField('user', {
        name: getUserNameFromStorage(),
        color: getColorByName(getUserNameFromStorage()),
        mouseX: event.clientX,
        mouseY: event.clientY,
      })
    })
    return { provider, doc, currentUser }
  }, [docId])

  // 历史版本控制状态
  const [versions, setVersions] = React.useState([])
  const [latestVersion, setLatestVersion] = React.useState(null)
  const [currentVersion, setCurrentVersion] = React.useState(null)
  const [isAutoVersioning, setIsAutoVersioning] = React.useState(false)
  const [hasChanges, setHasChanges] = React.useState(false)
  const [selectedVersion, setSelectedVersion] = React.useState(null) // 当前选中查看的版本

  // 版本更新处理函数
  const handleVersionUpdate = React.useCallback((data) => {
    console.log('Version update received:', data)
    const newVersions = data.versions || []
    const newLatestVersion = data.latestVersion
    const newCurrentVersion = data.currentVersion
    
    setVersions(newVersions)
    setIsAutoVersioning(data.versioningEnabled || false)
    setLatestVersion(newLatestVersion)
    setCurrentVersion(newCurrentVersion)
    
    // 只在初始化时（selectedVersion为null）设置默认选中版本
    // 避免在用户主动选择版本后被重置
    setSelectedVersion(prev => {
      console.log('Setting selected version, prev:', prev, 'newLatest:', newLatestVersion)
      if (prev === null && newLatestVersion !== null) {
        return newLatestVersion
      }
      // 如果当前选中的版本在新版本列表中不存在，则重置为最新版本
      if (prev !== null && newVersions.length > 0 && !newVersions.some(v => v.version === prev)) {
        return newLatestVersion
      }
      return prev
    })
  }, [])

  const editor = useEditor({
    immediatelyRender: false,
    editorProps: {
      attributes: {
        autocomplete: "off",
        autocorrect: "off",
        autocapitalize: "off",
        "aria-label": "请在此输入内容",
      }
    },
    extensions: [
      Document,
      Paragraph,
      Text,
      StarterKit.configure({
        history: false, // 在协同编辑中禁用撤销重做，避免冲突
        document: false, // 禁用默认的 document，使用自定义的
        paragraph: false, // 禁用默认的 paragraph，使用自定义的
        text: false, // 禁用默认的 text，使用自定义的
      }),
      Collaboration.configure({
        document: mainDoc, // Configure Y.Doc for collaboration
      }),
      // 添加协同光标扩展
      createCollaborationCursor(mainProvider, currentUser),
      TextAlign.configure({ types: ["heading", "paragraph"] }),
      Underline,
      TaskList,
      TaskItem.configure({ nested: true }),
      Highlight.configure({ multicolor: true }),
      Image,
      Typography,
      Superscript,
      Subscript,
      TextStyle,
      Color.configure({ types: [TextStyle.name] }),
      Table.configure({
        resizable: true,
        HTMLAttributes: {
          class: 'table-auto w-full border-collapse border border-gray-300',
        },
      }),
      TableRow.configure({
        HTMLAttributes: {
          class: 'border-b border-gray-300',
        },
      }),
      TableHeader.configure({
        HTMLAttributes: {
          class: 'bg-gray-100 font-bold text-left p-2 border border-gray-300',
        },
      }),
      TableCell.configure({
        HTMLAttributes: {
          class: 'p-2 border border-gray-300',
        },
      }),
      Selection,
      ImageUploadNode.configure({
        accept: "image/*",
        maxSize: MAX_FILE_SIZE,
        limit: 3,
        upload: handleImageUpload,
        onError: (error) => console.error("Upload failed:", error),
      }),
      TrailingNode,
      Link.configure({ openOnClick: false }),
      // 添加评论扩展
      createCommentsExtension(mainProvider, (threadId) => {
        console.log('Thread clicked:', threadId)
        
        // 添加位置验证和错误处理
        if (!editor || !threadId) {
          console.warn('Invalid editor or threadId in thread click handler')
          return
        }
        
        try {
          // 验证编辑器状态
          if (!editor.state || !editor.state.doc) {
            console.warn('Editor state is not ready')
            return
          }
          
          // 安全地处理线程选择
          editor.chain().focus().selectThread({ 
            id: threadId, 
            updateSelection: false 
          }).run()
        } catch (error) {
          console.error('Error handling thread click:', error)
        }
      }),
      // 添加历史版本控制扩展 - 确保在协同编辑扩展之后加载
      createHistoryExtension(mainProvider, handleVersionUpdate),
    ],
  },[docId]) // 依赖 docId，当它改变时，重新创建编辑器实例
    // 当docId为new时，不进行协同编辑，文档初始化为空
    // if (docId === 'new') {
    //   editor.commands.setContent({ type: 'doc', content: [] });
    // }

  // 历史版本控制函数（在 editor 创建后定义）
  const saveVersion = React.useCallback((name) => {
    if (!mainProvider || !name) return false
    try {
      console.log('Creating version with name:', name)
      
      // 根据官方文档，使用 provider.sendStateless 发送 version.create 请求
      mainProvider.sendStateless(
        JSON.stringify({
          action: 'version.create',
          name: name,
        })
      )
      
      return true
    } catch (error) {
      console.error('Failed to save version:', error)
      return false
    }
  }, [mainProvider])

  const toggleVersioning = React.useCallback(() => {
    if (!editor) return false
    try {
      editor.commands.toggleVersioning()
      return true
    } catch (error) {
      console.error('Failed to toggle versioning:', error)
      return false
    }
  }, [editor])

  // 预览版本（不创建新版本）
  const previewVersion = React.useCallback((version) => {
    if (!mainProvider || version === null) return false
    try {
      // 发送预览请求
      mainProvider.sendStateless(
        JSON.stringify({
          action: 'version.preview',
          version: version,
        })
      )
      setSelectedVersion(version)
      return true
    } catch (error) {
      console.error('Failed to preview version:', error)
      return false
    }
  }, [mainProvider])

  // 恢复到指定版本（会创建新版本）
  const revertToVersion = React.useCallback((version, versionData) => {
    if (!mainProvider || version === null) return false
    try {
      const versionTitle = versionData ? versionData.name || new Date(versionData.date).toLocaleString() : `Version ${version}`
      
      console.log('Reverting to version:', version, 'with title:', versionTitle)
      
      // 根据官方文档，使用 provider.sendStateless 发送 document.revert 请求
      mainProvider.sendStateless(
        JSON.stringify({
          action: 'document.revert',
          version: version,
          currentVersionName: `Unsaved changes before revert to ${versionTitle}`,
          newVersionName: `Revert to ${versionTitle}`,
        })
      )
      
      // 恢复后，重置选中版本为最新版本（恢复操作会创建新的最新版本）
      setSelectedVersion(null) // 让系统自动设置为新的最新版本
      return true
    } catch (error) {
      console.error('Failed to revert to version:', error)
      return false
    }
  }, [mainProvider])

  // 回到最新版本
  const backToLatest = React.useCallback(() => {
    if (!mainProvider || latestVersion === null) return false
    try {
      // 发送最新版本预览请求
      mainProvider.sendStateless(
        JSON.stringify({
          action: 'version.preview',
          version: latestVersion,
        })
      )
      setSelectedVersion(latestVersion)
      return true
    } catch (error) {
      console.error('Failed to back to latest:', error)
      return false
    }
  }, [mainProvider, latestVersion])

  // 设置协同编辑回调
  React.useEffect(() => {
    if (!mainProvider) return

    const handleConnect = () => {
      console.log('协同编辑连接成功')
    }

    const handleSynced = () => {
      console.log('协同编辑同步完成')
      // 只在第一次同步且文档为空时不设置初始内容
      if (!mainDoc.getMap('config').get('initialContentLoaded') && editor) {
        mainDoc.getMap('config').set('initialContentLoaded', true)
        // 如果有传入的初始内容，则设置它
        if (content && Object.keys(content).length > 0) {
          editor.commands.setContent(content)
        }
      }
      
      // 同步完成后，检查历史版本状态
      if (editor && editor.storage.collabHistory) {
        console.log('History storage after sync:', editor.storage.collabHistory)
      }
    }

    const handleDisconnect = () => {
      console.log('协同编辑连接断开')
    }

    const handleError = (error) => {
      console.error('协同编辑错误:', error)
    }

    const handleStatus = (status) => {
      console.log('协同编辑状态变化:', status)
    }

    const handleAuthenticated = () => {
      console.log('协同编辑认证成功')
    }

    const handleAuthenticationFailed = (error) => {
      console.error('协同编辑认证失败:', error)
    }

    // 处理无状态消息（包括版本恢复响应）
    const handleStateless = (data) => {
      try {
        const payload = JSON.parse(data.payload)
        console.log('Stateless message received:', payload)
        
        if (payload.action === 'document.reverted') {
          console.log('Document reverted to version:', payload.version)
          // 版本恢复成功，更新当前版本
          setSelectedVersion(payload.version)
          setHasChanges(false) // 重置未保存标志
        } else if (payload.action === 'version.created') {
          console.log('New version created:', payload.version)
          // 新版本创建后，更新版本信息
          setHasChanges(false)
        }
      } catch (error) {
        console.error('Error parsing stateless message:', error)
      }
    }

    // 添加更多事件监听
    mainProvider.on('connect', handleConnect)
    mainProvider.on('synced', handleSynced)
    mainProvider.on('disconnect', handleDisconnect)
    mainProvider.on('error', handleError)
    mainProvider.on('status', handleStatus)
    mainProvider.on('authenticated', handleAuthenticated)
    mainProvider.on('authenticationFailed', handleAuthenticationFailed)
    mainProvider.on('stateless', handleStateless)

    // 强制连接
    if (mainProvider.status === 'disconnected') {
      console.log('强制重新连接协同编辑服务')
      mainProvider.connect()
    }

    return () => {
      mainProvider.off('connect', handleConnect)
      mainProvider.off('synced', handleSynced)
      mainProvider.off('disconnect', handleDisconnect)
      mainProvider.off('error', handleError)
      mainProvider.off('status', handleStatus)
      mainProvider.off('authenticated', handleAuthenticated)
      mainProvider.off('authenticationFailed', handleAuthenticationFailed)
      mainProvider.off('stateless', handleStateless)
    }
  }, [mainProvider, mainDoc, editor, content])

  // 设置版本预览监听器
  React.useEffect(() => {
    if (!mainProvider || !editor) return

    // 使用官方推荐的 watchPreviewContent 来监听版本预览内容变化
    const unbindWatchContent = watchPreviewContent(mainProvider, (content) => {
      console.log('Version preview content received:', content)
      if (editor && content) {
        // 设置预览内容到编辑器
        editor.commands.setContent(content)
      }
    })

    return () => {
      unbindWatchContent()
    }
  }, [mainProvider, editor])

  // 允许父组件通过 ref 调用 clearContent
  React.useImperativeHandle(ref, () => ({
    clearContent: () => {
      if (editor) {
        editor.commands.setContent({ type: 'doc', content: [] });
      }
    }
  }), [editor]);
  //在协同编辑模式下，会出现重复设置内容的问题，所以需要手动设置内容
  //   React.useEffect(() => {
  //   if (editor && content) {
  //     // 只有内容不一致时才 setContent，避免光标跳动
  //     if (JSON.stringify(editor.getJSON()) !== JSON.stringify(content)) {
  //       editor.commands.setContent(content);
  //     }
  //   }
  // }, [content, editor]);

  // 监听内容变化并回调
  React.useEffect(() => {
    if (!editor || !onContentChange) return;
    const updateHandler = () => {
      onContentChange(editor.getJSON());
    };
    editor.on('update', updateHandler);
    return () => editor.off('update', updateHandler);
  }, [editor, onContentChange]);

  // 监听文档变化以检测是否有未保存的修改
  React.useEffect(() => {
    if (!mainProvider || !mainProvider.document) return

    const onUpdate = () => {
      setHasChanges(true)
    }

    const onSynced = () => {
      mainProvider.document.on('update', onUpdate)
    }

    mainProvider.on('synced', onSynced)

    return () => {
      mainProvider.off('synced', onSynced)
      if (mainProvider.document) {
        mainProvider.document.off('update', onUpdate)
      }
    }
  }, [mainProvider]);

  const bodyRect = useCursorVisibility({
    editor,
    overlayHeight: toolbarRef.current?.getBoundingClientRect().height ?? 0,
  })

  React.useEffect(() => {
    if (!isMobile && mobileView !== "main") {
      setMobileView("main")
    }
  }, [isMobile, mobileView])

  // 清理 provider
  React.useEffect(() => {
    return () => {
      mainProvider?.destroy()
    }
  }, [mainProvider])

  return (
    <EditorContext.Provider value={{ editor }}>
      <div style={{ display: 'flex', height: '100%' }}>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
          {/* 工具栏始终显示 */}
          <Toolbar
            ref={toolbarRef}
            style={
              isMobile
                ? {
                    bottom: `calc(100% - ${windowSize.height - bodyRect.y}px)`,
                  }
                : {}
            }>
            {mobileView === "main" ? (
              <MainToolbarContent
                onHighlighterClick={() => setMobileView("highlighter")}
                onLinkClick={() => setMobileView("link")}
                isMobile={isMobile} />
            ) : (
              <MobileToolbarContent
                type={mobileView === "highlighter" ? "highlighter" : "link"}
                onBack={() => setMobileView("main")} />
            )}
            {/* 添加评论和历史版本按钮 */}
            <ToolbarSeparator />
            <ToolbarGroup>
              <CommentButton editor={editor} />
              <Tooltip content={showComments ? '隐藏评论' : '显示评论'}>
                <Button 
                  data-style="ghost" 
                  tooltip={showComments ? '隐藏评论' : '显示评论'}
                  onClick={() => setShowComments(!showComments)}
                  data-active={showComments}
                  data-text-trim="on"
                >
                  <span className="tiptap-button-text">
                    {showComments ? '隐藏评论' : '显示评论'}
                  </span>
                </Button>
              </Tooltip>
              <Tooltip content="历史版本">
                <Button 
                  data-style="ghost" 
                  onClick={() => setShowHistory(!showHistory)}
                  data-active={showHistory}
                >
                  <HistoryIcon className="tiptap-button-icon" />
                </Button>
              </Tooltip>
              <Tooltip content={showHistory ? '隐藏历史面板' : '显示历史面板'}>
                <Button 
                  data-style="ghost" 
                  tooltip={showHistory ? '隐藏历史面板' : '显示历史面板'}
                  onClick={() => setShowHistory(!showHistory)}
                  data-active={showHistory}
                  data-text-trim="on"
                >
                  <span className="tiptap-button-text">
                    {showHistory ? '隐藏历史面板' : '显示历史面板'}
                  </span>
                </Button>
              </Tooltip>
            </ToolbarGroup>
          </Toolbar>
          {/* 浮动菜单始终显示 */}
          {editor && <BubbleMenu className="bubble-menu" tippyOptions={{ duration: 100 }} editor={editor}>
            <MarkButton type="bold" />
            <MarkButton type="italic" />
            <MarkButton type="strike" />
            <HeadingDropdownMenu levels={[1, 2, 3, 4]} />
            {!isMobile ? (
              <ColorHighlightPopover />
            ) : (
              <ColorHighlightPopoverButton onClick={onHighlighterClick} />
            )}
            <ColorTextPopover />
          </BubbleMenu>}
          {/* 内容区域 */}
          <div className="content-wrapper" style={{ flex: 1 }}>
            {editor && <EditorContent editor={editor} role="presentation" className="simple-editor-content" />}
          </div>
        </div>
        {/* 评论侧边栏 */}
        {showComments && (
          <div style={{ width: '300px', borderLeft: '1px solid #e0e0e0' }}>
            <CommentsSidebar editor={editor} provider={mainProvider} />
          </div>
        )}
        {/* 历史版本控制面板 */}
        {showHistory && (
          <div style={{ 
            minWidth: '320px', 
            maxWidth: '400px', 
            borderLeft: '1px solid #e0e0e0', 
            padding: '1rem',
            display: 'flex',
            flexDirection: 'column'
          }}>
            <div className="history-panel">
              <div className="option-group">
                <div className="label-large">自动版本控制</div>
                <div className="switch-group">
                  <label>
                    <input
                      type="radio"
                      name="auto-versioning"
                      onChange={() => !isAutoVersioning && toggleVersioning()}
                      checked={isAutoVersioning}
                    />
                    启用
                  </label>
                  <label>
                    <input
                      type="radio"
                      name="auto-versioning"
                      onChange={() => isAutoVersioning && toggleVersioning()}
                      checked={!isAutoVersioning}
                    />
                    禁用
                  </label>
                </div>
              </div>
              
              <hr />
              
              <div className="option-group">
                <div className="label-large">手动版本控制</div>
                <div className="label-small">对文档进行修改后，可以手动保存新版本。</div>
                <form className="commit-panel" onSubmit={(e) => {
                  e.preventDefault()
                  const input = e.target.querySelector('input')
                  if (input.value.trim()) {
                    saveVersion(input.value.trim())
                    input.value = ''
                  }
                }}>
                  <input 
                    disabled={!hasChanges} 
                    type="text" 
                    placeholder="版本名称" 
                  />
                  <Button 
                    disabled={!hasChanges} 
                    type="submit"
                    data-style="default"
                  >
                    创建版本
                  </Button>
                </form>
              </div>
              
              <hr />
              
              <div className="option-group">
                <div className="label-large">版本历史</div>
                <div className="label-small">当前共有 {versions.length} 个版本</div>
                
                {/* 当前查看版本提示和操作 */}
                {selectedVersion !== null && selectedVersion !== latestVersion && (
                  <div style={{ 
                    padding: '0.5rem', 
                    backgroundColor: '#f0f8ff', 
                    border: '1px solid #b0d4f1', 
                    borderRadius: '0.25rem',
                    marginBottom: '0.5rem'
                  }}>
                    <div style={{ fontSize: '0.75rem', color: '#1e40af', marginBottom: '0.25rem' }}>
                      正在查看历史版本 {selectedVersion + 1}
                    </div>
                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                      <Button 
                        data-style="ghost"
                        onClick={backToLatest}
                        style={{ 
                          fontSize: '0.75rem', 
                          padding: '0.25rem 0.5rem',
                          backgroundColor: '#f3f4f6',
                          border: '1px solid #d1d5db',
                          color: '#374151'
                        }}
                      >
                        回到最新版本
                      </Button>
                      <Button 
                        data-style="default"
                        onClick={() => {
                          const version = versions.find(v => v.version === selectedVersion)
                          if (window.confirm('确定要恢复到此版本吗？未保存的更改将丢失。')) {
                            revertToVersion(selectedVersion, version)
                          }
                        }}
                        style={{ 
                          fontSize: '0.75rem', 
                          padding: '0.25rem 0.5rem',
                          backgroundColor: '#3b82f6',
                          border: '1px solid #3b82f6',
                          color: 'white'
                        }}
                      >
                        恢复此版本
                      </Button>
                    </div>
                  </div>
                )}
                {selectedVersion !== null && selectedVersion === latestVersion && (
                  <div style={{ 
                    padding: '0.5rem', 
                    backgroundColor: '#f0fff0', 
                    border: '1px solid #90ee90', 
                    borderRadius: '0.25rem',
                    marginBottom: '0.5rem'
                  }}>
                    <div style={{ fontSize: '0.75rem', color: '#006400' }}>
                      当前查看最新版本 {selectedVersion + 1}
                    </div>
                  </div>
                )}
                
                {versions.length > 0 && (
                  <div className="versions-group" style={{overflow: 'auto' }}>
                    {versions.slice().reverse().map((version, index) => (
                      <button 
                        key={version.version}
                        className={selectedVersion === version.version ? 'is-active' : ''}
                        onClick={() => {
                          console.log('Clicking version:', version.version, 'Current selected:', selectedVersion)
                          previewVersion(version.version)
                        }}
                      >
                        {version.name || `版本 ${version.version + 1}`}
                        <span>{new Date(version.date).toLocaleString()}</span>
                      </button>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
      </div>
    </EditorContext.Provider>
  );
})
export default SimpleEditor;
